package beastick.configurator.types;

//Copyright 2008 Tofig Kareemov, estereos@gmail.com
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

import beastick.configurator.CConfigurator;
import beastick.utility.CStringParameterizer;

public class CParameterizedString
{
  public static CParameterizedString oParameterizedString = new CParameterizedString();
  public String sValue = "";

  public CParameterizedString()
  {
    super();
  }

  public CParameterizedString(String isValue, CConfigurator oConfigurator)
  {
    super();
    sValue = Convert(isValue, oConfigurator);
  }

  public String toString()
  {
    return sValue;
  }

  public String Convert(String sValue, CConfigurator oConfigurator)
  {
    CStringParameterizer sResult = new CStringParameterizer(sValue);
    String sParameterFullName = "";
    String sParameterName = "";
    int iParamStart = 0;
    int iParamEnd = 0;
    for (int i = 0; i < 1000; ++i)
    {
      iParamEnd = sResult.Get().indexOf("}");
      if (iParamEnd > 0)
      {
        iParamStart = sResult.Get().substring(0, iParamEnd).lastIndexOf("${");
      }
      if (iParamEnd <= iParamStart)
      {
        break;
      }
      sParameterFullName = sResult.Get().substring(iParamStart, iParamEnd + 1);
      sParameterName = sResult.Get().substring(iParamStart + 2, iParamEnd);
      sResult.ParameterCompiled(sParameterFullName, oConfigurator
        .GetValueAsString(sParameterName));
    }
    sResult.UnknownCompiled("${", "}");
    return sResult.Get();
  }

  public static String StringValueOf(String sValue, CConfigurator oConfigurator)
  {
    synchronized (oParameterizedString)
    {
      return oParameterizedString.Convert(sValue, oConfigurator);
    }
  }

  public static CParameterizedString valueOf(String sValue,
                                             CConfigurator oConfigurator)
  {
    return new CParameterizedString(sValue, oConfigurator);
  }
}